import 'dart:async';

import 'package:cleanetc_client/core/utils/dialog.dart';
import 'package:cleanetc_client/core/utils/toast.dart';
import 'package:cleanetc_client/mvvm/api/repository.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:oktoast/oktoast.dart';

class BaseApiViewModel extends ChangeNotifier {
  final _loading = LoadingDialog();
  ApiService apiService = ApiService();

  late BuildContext context;

  dynamic doGet(String url, [Map<String, dynamic>? params]) {
    return apiService.doGet(url, params).listen((data) {
      hideLoading();
    }, onError: (e) {
      showErrorToast(e.toString());
      hideLoading();
    });
  }

  StreamSubscription doPost(String url, Map<String, dynamic> params) {
    showLoading();
    return apiService.doPost(url, params).listen((data) {
      hideLoading();
    }, onError: (e) {
      hideLoading();
    }, onDone: () {
      hideLoading();
    });
  }

  BaseApiViewModel(this.context);

  bool loadingDisplayable = true;
  bool toastDisplayable = true;

  void showLoading() {
    if (loadingDisplayable) _loading.show(context);
  }

  void hideLoading() {
    _loading.hide(context);
  }

  void showErrorToast(e) {
    if (toastDisplayable) ToastUtils.error(e);
  }
}
